# -*- coding: UTF-8 -*-
import subprocess,time,threading,json

#
# Update the latest package dependency files 
# Author[chuan_fu]
#
demo=open("../demo.json","r")
demo=demo.read()
demo=json.loads(demo)
result_b=""
def main():
	global demo
	global result_b
	while True:
		try:
			result=""
			result=subprocess.run(["git","pull"])
		except subprocess.TimeoutExpired as e:
			pass
		else:
			break
	while True:
		try:
			result=""
			result_b=""
			result=subprocess.Popen(["git","branch","-r"],stdout=subprocess.PIPE)
			result,error=result.communicate()
		except subprocess.TimeoutExpired as e:
			pass
		else:
			result=result.decode("utf-8")
			version=result.split("\n")
			for x in range(0,len(version)):
				version[x]=version[x].strip()
				if version[x]=="":
					del version[x]
			result_b=version[len(version)-1]
			demo["version"]=demo["version"].replace("\\","")
			if demo["version"]==result_b :
				exit()
			break

	while True:
		try:
			res=""
			res=subprocess.run(["git","merge",result_b])
		except subprocess.TimeoutExpired as e:
			pass
		else:
			time.sleep(2)
			print(f"update successfully to {result_b}")
			break

def chmod():
	try:
		res=""
		res=subprocess.run(["chmod","-R","777","../../"])
	except subprocess.TimeoutExpired as e:
		print("edit chmod error")

def version():
	global result_b
	global demo
	demo["version"]=result_b
	demo=json.dumps(demo,indent=4)
	with open("../demo.json","w") as d:
		d.write(demo)

if __name__ == '__main__':
	main()
	chmod()
	version()
	